<?php
class PublicAction extends AdminBaseAction{
	//--登录界面
	function index(){
		redirect(__URL__.'/Login');	
	}
	
	//登录界面
	 function login(){
		header("Content-Type:text/html; charset=utf-8");
		if( $this->isLogin() ){
			redirect( __URL__.'/adminIndex' );
		}
		$this->display();
		$this->showLoginAuthorize();
	}
	
	function showCode(){
		$AdminName = trim($_GET['username']);
		$m = D('Admin/Admin');
		$showCode = $m->hasCode($AdminName);
		$this->ajaxReturn(null, '' , $showCode);
	}
	
	//退出系统
	function logOut(){
		header("Content-Type:text/html; charset=utf-8");
		$options['LogType'] = 8;
		$options['UserAction'] = '退出管理后台';
		WriteLog(session("AdminName"),$options);
		session("AdminID", null);
		session("AdminName", null);
		session("AdminGroupID", null);
		session("AdminGroupName", null);
		session("AdminMemberID", null);
		redirect(__URL__.'/Login');
	}
	
	 function checkLogin(){
	 	header("Content-Type:text/html; charset=utf-8");
	 	
		$AdminName = trim($_POST['username']); 
		$AdminPassword = trim($_POST['password']); 
		$verifyCode = trim($_POST['verifycode']);
		
		if(empty($AdminName)){
			session('verify', rand(1000, 9999) );
			$this->ajaxReturn(null, '用户名不能为空!' , 0);
		}
		
		if(empty($AdminPassword)){
			session('verify', rand(1000, 9999) );
			$this->ajaxReturn(null, '密码不能为空!' , 0);
		}
		
		$admin = D('Admin/Admin');
		$showCode = $admin->hasCode($AdminName);
		if( $showCode == 1 ){ //只有等于1时才需要显示验证码
			if(empty($verifyCode)){
				session('verify', rand(1000, 9999) );
				$this->ajaxReturn(1, '请输入验证码!' , 0);
			}
			
			$verifyCode2 = session('verify');
			if(md5($verifyCode) != $verifyCode2){
				session('verify', rand(1000, 9999) );
				$this->ajaxReturn(1, '验证码错误!' , 0);
			}
		}
		
		$options['LogType'] = 8;
		$options['UserAction'] = '管理员登录';
		//0: 用户名或密码错误，1：用户被锁定，2:用户组不存在，数组：认证成功
		$result = $admin->checkLogin($AdminName, md5($AdminPassword) );
		if( $result == 0 ){
			WriteLog("管理员登录失败，用户名：$AdminName 或密码： $AdminPassword 错误",$options);
			$showCode = $admin->hasCode($AdminName);
			$this->ajaxReturn($showCode, '用户名或密码错误!' , 0);
		}else if($result == 1){
			WriteLog("管理员登录失败，$AdminName 已被锁定",$options);
			$this->ajaxReturn(null, '账户已被锁定!' , 1);
		}else if($result == 2){
			WriteLog("管理员登录失败，管理组不存在",$options);
			$this->ajaxReturn(null, '管理组不存在' , 2);
		}else if( is_array($result) ){ //认证成功
			$admin->UpdateLogin($result['AdminID']);
			WriteLog('管理员登录成功 '.$AdminName, $options);
			session('AdminID', $result['AdminID']);
			session('AdminMemberID', $result['MemberID']);
			session('AdminName', $result['AdminName']);
			session('AdminGroupID', $result['AdminGroupID']);
			session('AdminGroupName', $result['AdminGroupName']);
			session('verify', rand(1000, 9999));
			$this->ajaxReturn(rand(1000, 9999), '登录成功' , 3);
		}
	}
	
	//获取当前MenuTopID
	private function getCurrentMenuTopID(){
		if( isset( $_GET['MenuTopID']  ) ){
			$id = $_GET['MenuTopID'];
			cookie("MenuTopID", $id);
		}else if( cookie("MenuTopID") ){
			$id = cookie("MenuTopID");
		}else{
			$id = 1;  //默认为1
		}
		return $id;
	}
	
	function adminTop(){
		header("Content-Type:text/html; charset=utf-8");
		$m = D('Admin/MenuTop');
		$gid = session('AdminGroupID');
		if( $gid == 1){ //超级管理员拥有所有权限
			$MenuTop = $m->getMenuTop( array("MenuOwner"=>1) );
		}else{
			$MenuTop = $m->getMenuTopPurview(1,  $gid);
		}
		$MenuTopID = $this->getCurrentMenuTopID();
		$this->assign('MenuTopID',$MenuTopID);
		$this->assign("MenuTop", $MenuTop );
		$this->display();
	}
	
	function adminLeft(){
		header("Content-Type:text/html; charset=utf-8");
		$MenuTopID = $this->getCurrentMenuTopID();
		$mg = D('Admin/MenuGroup');
		$m = D('Admin/Menu');
		$gid = session('AdminGroupID');
		if( $gid == 1){ //超级管理员
			$MenuGroup = $mg->getMenuGroup($MenuTopID);
			$Menu = $m->getMenu();
		}else{
			$MenuGroup = $mg->getMenuGroupPurview(1, $gid, $MenuTopID);
			$Menu = $m->getMenuPurview(1, $gid);
		}
		
		//内容管理需要加载树形频道========================================
		if( $MenuTopID == 3 ){
			$c = D('Admin/Channel');
			$Channel = ($gid==1) ? $c->getChannelList(0,-1,'') : $c->getChannelPurview(1, $gid, '');
			$n = count($Channel);
			
			//找出ChannelDepth最大值===========================
			$maxDepth = -9999;
			for($j = 0; $j < $n; $j++){
				if( $Channel[$j]['ChannelDepth'] > $maxDepth ) {
					$maxDepth = $Channel[$j]['ChannelDepth'];
				}
			}
			//===========================================
			
			for($i = 0; $i < $n; $i++){
				$Channel[$i]['HasChild'] = $c->hasChildChannel($Channel[$i]['ChannelID']);
				$Channel[$i]['ChannelDepth'] = ($maxDepth - $Channel[$i]['ChannelDepth'] + 1);
			}
			$this->assign('Channel', $Channel);
		}
		//========================================================
		$this->assign('MenuTopID',$MenuTopID);
		
		$this->assign('Menu', $Menu);
		$this->assign('MenuGroup',$MenuGroup);
		
		$this->assign("AdminName", session("AdminName") );
		$this->assign("AdminGroupName", session("AdminGroupName") );
		
		$this->display();
	}
	
	//页脚
	function adminBottom(){
		header("Content-Type:text/html; charset=utf-8");
		$this->display();
	}
	
	//管理首页
	function adminIndex(){
		header("Content-Type:text/html; charset=utf-8");
		$MenuTopID = $this->getCurrentMenuTopID();
		$this->assign('MenuTopID', $MenuTopID);
		$this->display();
	}
	
	/**
	 * 设置语言
	 */
	function setLanguage(){
		redirect(__URL__.'/AdminIndex');
	}

	//管理首页
	function welcome(){
		header("Content-Type:text/html; charset=utf-8");
		//获取服务器信息================
		import('@.Common.YdServerInfo');
		$s = new YdServerInfo();
		$info = $s->getServerInfo();
		$this->assign('Server', $info);
		//==========================
		
		//检测是否需要升级==================================
		/*
		import('@.Common.YdUpgrade');
		$u = new YdUpgrade($this->YouDianCMSVersion);
		$LastestVersion = $u->getLatestVersion();
		$LastestDate = $u->getLatestDate();
		$needUpgrade = $u->needUpgrade() ? 1 : 0;  //是否需要升级
		$this->assign('LastestDate', $LastestDate);
		$this->assign('LastestVersion', $LastestVersion);
		$this->assign('NeedUpgrade', $needUpgrade);
		*/
		//=============================================
		
		//获取管理员信息==============================
		$admin = D('Admin/Admin');
		$adminInfo = $admin->find( session('AdminID') );
		$this->assign('LastLoginTime', $adminInfo['LastLoginTime']);
		$this->assign('LastLoginIP', $adminInfo['LastLoginIP']);
		$this->assign('LoginCount', $adminInfo['LoginCount']);
		//========================================
		
		$this->display();
		
		//7.1版，将放在登陆界面显示
		//$this->showAuthorize();
	}
	
	//网站目录权限检测
	public function dirDetection(){
		$config = $this->getWapTpl();
		$wapConfigFile = $config['pWapConfig'];
		$config = $this->getHomeTpl();
		$homeConfigFile = $config['pHomeConfig'];
		//flag=0表示不检测可执行权限
		$list = array(
				//array('Name'=>'网站根目录',        'Dir'=>'./',                 'Flag'=>0, 'Suggest'=>'只读', 'Remark'=>'网站放在wwwroot目录下，将wwwroot设为只读，如果要生成网站地图，需要文件sitemap.html、sitemap.xml、sitemap.txt设为可读写'),
				array('Name'=>'数据目录',  'Dir'=>APP_DATA_PATH,    'Flag'=>1, 'Suggest'=>"可读写、关闭执行权限",  'Remark'=>'数据目录，存放数据库备份sql、全站备份zip、静态缓存html、系统缓存runtime等'),
				array('Name'=>'系统缓存目录',  'Dir'=>APP_DATA_PATH.'runtime/',    'Flag'=>1, 'Suggest'=>"可读写、关闭执行权限",  'Remark'=>''),
				array('Name'=>'全站备份目录',  'Dir'=>APP_DATA_PATH.'zip/',    'Flag'=>1, 'Suggest'=>"可读写、关闭执行权限",  'Remark'=>''),
				array('Name'=>'数据库备份目录',  'Dir'=>APP_DATA_PATH.'sql/',    'Flag'=>1, 'Suggest'=>"可读写、关闭执行权限",  'Remark'=>''),
				array('Name'=>'网站地图目录',  'Dir'=>APP_DATA_PATH.'map/',    'Flag'=>1, 'Suggest'=>"可读写、关闭执行权限",  'Remark'=>''),
				
				array('Name'=>'上传目录',           'Dir'=>'./Upload/',     'Flag'=>1, 'Suggest'=>"可读写、关闭执行权限",  'Remark'=>'上传的文件都存在此目录！'),
				array('Name'=>'系统配置目录',     'Dir'=>CONF_PATH,  'Flag'=>1, 'Suggest'=>"可读写、关闭执行权限",  'Remark'=>'系统配置文件，如：数据库配置、伪静态配置等'),
				array('Name'=>'电脑网站模板目录',  'Dir'=>TMPL_PATH.'Home/',  'Flag'=>1, 'Suggest'=>'只读',  'Remark'=>'如果需要在后台修改模板文件，才开启写入权限，建议设置为只读'),
				array('Name'=>'手机网站模板目录',  'Dir'=>TMPL_PATH.'Wap/',  'Flag'=>1, 'Suggest'=>'只读',  'Remark'=>'如果需要在后台修改模板文件，才开启写入权限，建议设置为只读'),
					
				array('Name'=>'电脑网站模板配置',  'Dir'=>$homeConfigFile,  'Flag'=>0, 'Suggest'=>'可读写',  'Remark'=>'如要在后台使用【模板管理】-【电脑网站管理】-【模板设置】，请开启写入权限'),
				array('Name'=>'手机网站模板配置',  'Dir'=>$wapConfigFile,  'Flag'=>0, 'Suggest'=>'可读写',  'Remark'=>'如要在后台使用【模板管理】-【手机网站管理】-【模板设置】，请开启写入权限'),
					
				//array('Name'=>'xml地图',  'Dir'=>'./sitemap.xml',  'Flag'=>0, 'Suggest'=>'可读写',  'Remark'=>''),
				//array('Name'=>'txt地图',  'Dir'=>'./sitemap.txt',  'Flag'=>0, 'Suggest'=>'可读写',  'Remark'=>''),
				//array('Name'=>'html地图',  'Dir'=>'./sitemap.html',  'Flag'=>0, 'Suggest'=>'可读写',  'Remark'=>''),
		);
		
		$n = count($list);
		for($i=0; $i < $n; $i++){
			if( file_exists($list[$i]['Dir']) ){
				$list[$i]['IsWritable'] = @yd_is_writable( $list[$i]['Dir'] );
				if( $list[$i]['Flag'] == 1 ){
					$list[$i]['IsExecutable'] = @yd_is_executable( $list[$i]['Dir'] );
				}
				$list[$i]['FileExist'] = 1;
			}else{
				$list[$i]['FileExist'] = 0;
			}
		}
		$this->assign('DirList', $list);
		$this->display();
	}
	
	private function showLoginAuthorize(){
		$hasChanged = $this->loginFileHasChanged();
		if($hasChanged){
			$AuthorizeScript="<script>
			$(document).ready(function(){
				$('#username').attr('disabled',true);
			 	$('#password').attr('disabled',true);
			 	$('.buttonface').attr('disabled',true);
			 	alert('非法篡改版权文件！');
			});
			</script>";
			echo $AuthorizeScript;  //直接输出，防止删除
		}
		
		//$_SERVER['HTTP_HOST']; //若端口号为非80端口，输出回包含端口号
		$para = '?version='.C('CMSVersion').'&host='.$_SERVER['HTTP_HOST'].'&os='.PHP_OS;
		$para .= '&cen='.C('CMSEnName').'&v=4';
		foreach (glob("./Data/*.id") as $filename) {
			$mid = basename($filename, '.id');
			if( is_numeric($mid)){
				$para .= '&mid='.$mid;
				break;
			}
		}
		$para .= '&time='.time(); //防止缓存
		$authUrl = "http://auth.youdiancms.com/authorize.php$para";
		$AuthorizeScript="<script>
			$(document).ready(function(){
				setTimeout(function(){
					$.getJSON('{$authUrl}&callback=?', function(data){
						$('#AuthorizeImage').html(data['AuthorizeImage']);
					});
				}, 350);
			});
		</script>";
		echo $AuthorizeScript;  //直接输出，防止删除
	}
	
	//检查登陆文件是否被篡改
	private function loginFileHasChanged(){
		return false;
	}
	
	//输出授权
	private function showAuthorize(){
		//$_SERVER['HTTP_HOST']; //若端口号为非80端口，输出回包含端口号
		$para = '?version='.C('CMSVersion').'&host='.$_SERVER['HTTP_HOST'].'&os='.PHP_OS;
		$para .= '&cen='.C('CMSEnName').'&v=2'; //v=1: 验证的版本号，2表示采用在客户端ajax验证
		foreach (glob("./Data/*.id") as $filename) {
			$mid = basename($filename, '.id');
			if( is_numeric($mid)){
				$para .= '&mid='.$mid;
				break;
			}
		}
		$para .= '&time='.time(); //防止缓存
		$authUrl = "http://auth.youdiancms.com/authorize.php$para";
		$AuthorizeScript="<script>
		$(document).ready(function(){
			getAuthorize();
			function getAuthorize(){
				jQuery.ajax({url: '{$authUrl}', type: 'GET',timeout: 15*1000,dataType:'jsonp', jsonp: 'callback',
				jsonpCallback:'success_jsonpcallback',success: setAuthorize});
			}
			function setAuthorize(data){
				if(  jQuery('#AuthorizeText').length <= 0 ){
					alert('软件未授权');return;
				}else{
					if(data.data) { eval(data.data); }
					jQuery('#AuthorizeText').html(data.info);
					setTimeout(function(){
						if( data.info.indexOf( jQuery('#AuthorizeText').text() ) == -1 ){ alert(data.info); }
						setAuthorize(data); 
					}, 1000);
				}
			}
		});
		</script>";
		
		//旧方案：有很大的延时
		//$AuthorizeScript = @yd_curl_get($authUrl, null, 3);  //3秒超时
		//if( !empty($AuthorizeScript) && false !== stripos($AuthorizeScript, "#AuthorizeText") ){
		//	$AuthorizeScript = "<script>$AuthorizeScript</script>";
		//}else{
		//	$AuthorizeScript = "";
		//}
		//$AuthorizeScript = "<script src='http://auth.youdiancms.com/authorize.php$para'></script>";
		//$this->assign('AuthorizeScript', $AuthorizeScript);
		echo $AuthorizeScript;  //直接输出，防止删除
	}
	
	//在线升级
	function upgrade(){
		import('@.Common.YdUpgrade');
		$u = new YdUpgrade($this->YouDianCMSVersion);
		//存在最新版本才升级
		$b = $u->needUpgrade();
		if( $b == false ){
			$this->ajaxReturn(null, '已经是最新版本！', 2);	
		}		
		$b = $u->start();  //开始升级
		$u->deleteAll();  //升级完成删除，所有升级临时文件
		if($b){
			$this->ajaxReturn(null, '升级成功！', 1);
		}else{
			$this->ajaxReturn(null, '升级失败！', 0);
		}
	}
	
	//修改密码
	function pwd(){
		header("Content-Type:text/html; charset=utf-8");
		if( $_POST['Action'] == 'save'){ //保存
			$admin = D('Admin/Admin');
			$pwd1 = trim($_POST['pwd1']);  //原始密码
			$pwd2 = $_POST['pwd2'];
			$pwd3 = $_POST['pwd3'];
			if( empty($pwd1) ){
				$this->ajaxReturn(null, '原始密码不能为空!' , 0);
			}
			
			if( empty($pwd2) ){
				$this->ajaxReturn(null, '新密码不能为空!' , 0);
			}
			
			if( empty($pwd3) ){
				$this->ajaxReturn(null, '重复密码不能为空!' , 0);
			}
			
			if( $pwd2 != $pwd3 ){
				$this->ajaxReturn(null, '二次输入的密码不一致!' , 0);
			}
			
			if( $pwd1 == $pwd3 ){
				$this->ajaxReturn(null, '新密码不能和原始密码相同!' , 0);
			}
			$options['LogType'] = 8;
			$b = $admin->exist(session('AdminName'), md5($pwd1) ); //检查原始密码是否正确
			if(!$b){
				$options['UserAction'] = '修改密码';
				WriteLog(session('AdminName').'修改密码失败，原密码错误', $options);
				$this->ajaxReturn(null, '原密码错误!' , 0);
			}
			
			$adminID = session('AdminID');
			$r = $admin->where("AdminID=$adminID")->setField('AdminPassword', md5($pwd2) );
			if($r){
				$options['UserAction'] = '修改密码';
				WriteLog(session('AdminName').'修改密码成功', $options);
				$this->ajaxReturn(null, '修改密码成功!' , 1);
			}else{
				$this->ajaxReturn(null, '修改密码失败!' , 0);
			}
		}
		$this->assign('Action', __URL__.'/pwd');
		$this->display();
	}
	
	function browser(){
		header("Content-Type:text/html; charset=utf-8");
		$this->display();
	}
	
	//清除系统缓存
	function clearCache(){
		header("Content-Type:text/html; charset=utf-8");
		$action = strtolower( $_REQUEST['Action'] );
		$p['LogType']=7;
		cookie("MenuTopID", null); //当顶部菜单为清除缓存时，不记录为模板选中
		switch ($action){
			case 'systemcache':  //清除系统缓存
				if( YdCache::writeAll() ){
					$p['UserAction'] = '清除系统缓存';
					WriteLog('', $p);
					$this->ajaxReturn(null, '清除系统缓存成功！', 1);
				}else{
					$this->ajaxReturn(null, '清除系统缓存失败！没有写入权限', 0);
				}
				break;
			case 'modelcache':  //清除频道模型缓存
				if(YdCache::deleteTemp()){
					$p['UserAction'] = '清除频道模型缓存';
					WriteLog('', $p);
					$this->ajaxReturn(null, '清除频道模型缓存成功！', 1);
				}else{
					$this->ajaxReturn(null, '清除频道模型缓存失败！没有写入权限', 0);
				}
				break;
			case 'homecache': 
				if(YdCache::deleteHome()){
					$p['UserAction'] = '清除模板缓存';
					WriteLog('', $p);
					$this->ajaxReturn(null, '清除模板缓存成功！', 1);
				}else{
					$this->ajaxReturn(null, '清除模板缓存失败！没有写入权限', 0);
				}
				break;
			case 'wapcache':
				if(YdCache::deleteWap()){
					$p['UserAction'] = '清除模板缓存';
					WriteLog('', $p);
					$this->ajaxReturn(null, '清除模板缓存成功！', 1);
				}else{
					$this->ajaxReturn(null, '清除模板缓存失败！没有写入权限', 0);
				}
				break;
			case 'indexhtmlcache': //清除网站首页Html静态缓存
				if( YdCache::deleteHtml('index')){
					$p['UserAction'] = '清除首页Html缓存';
					WriteLog('', $p);
					$this->ajaxReturn(null, '清除首页Html缓存成功！', 1);
				}else{
					$this->ajaxReturn(null, '清除首页Html缓存失败！没有写入权限', 0);
				}
				break;
			case 'channelhtmlcache': //频道首页Html静态缓存
				if( YdCache::deleteHtml('channel') ){
					$p['UserAction'] = '清除频道首页Html缓存';
					WriteLog('', $p);
					$this->ajaxReturn(null, '清除频道首页Html缓存成功！', 1);
				}else{
					$this->ajaxReturn(null, '清除频道首页Html缓存失败！没有写入权限', 0);
				}
				break;
			case 'infohtmlcache': //信息页面Html静态缓存
				if(YdCache::deleteHtml('info')){
					$p['UserAction'] = '清除内容页面Html缓存';
					WriteLog('', $p);
					$this->ajaxReturn(null, '清除内容页面Html缓存成功！', 1);
				}else{
					$this->ajaxReturn(null, '清除内容页面Html缓存失败！没有写入权限', 0);
				}
				break;
			case 'allhtmlcache': //所有Html静态缓存
				if(YdCache::deleteHtml('all')){
					$p['UserAction'] = '清除全部Html缓存';
					WriteLog('', $p);
					$this->ajaxReturn(null, '清除全部Html缓存成功！', 1);
				}else{
					$this->ajaxReturn(null, '清除全部Html缓存失败！没有写入权限', 0);
				}
				break;
			case 'saveconfig': //保存缓存配置
				if( isset($_POST) ){  //保存配置到数据库
					if( !is_numeric( $_POST['INDEX_CACHE_TIME']) || 
							!is_numeric( $_POST['CHANNEL_CACHE_TIME']) ||
							!is_numeric( $_POST['INFO_CACHE_TIME'])
					){
						$this->ajaxReturn(null, '缓存时间必须为数字！', 0);
					}
					
					$htmlEnable = ($_POST['HTML_ENABLE'] == 1) ? true : false;
					$IndexCacheTime = $_POST['INDEX_CACHE_TIME'];
					$ChannelCacheTime = $_POST['CHANNEL_CACHE_TIME'];
					$InfoCacheTime = $_POST['INFO_CACHE_TIME'];
					$html = array (
							'HTML_CACHE_ON' => $htmlEnable,
							'HTML_CACHE_RULES'=> array(
									'index:index'=>array('{:group}/index_{0|get_language_mark}', $IndexCacheTime),
									'channel:index'=>array('{:group}/channel/{id}{jobid}{infoid}_{0|get_language_mark}_{0|get_para}', $ChannelCacheTime),
									'info:read'=>array('{:group}/info/{id}_{0|get_para}', $InfoCacheTime),
							)
					);					
					if( YdCache::writeCoreConfig($html) ){
						YdCache::deleteAll(); //必须清除缓存，否则无法重新读取core.php
						$p['UserAction'] = '保存缓存配置';
						$p['LogType'] = 4;
						WriteLog('', $p);
						$this->ajaxReturn(null, '保存配置成功!' , 1);
					}else{
						$this->ajaxReturn(null, '保存配置失败!' , 0);
					}
				}
				break;
		}
		$core = C('HTML_CACHE_RULES');
		$HtmlEnable = C('HTML_CACHE_ON') ? 1 : 0;
		$IndexCacheTime = intval($core['index:index'][1]);
		$ChannelCacheTime = intval($core['channel:index'][1]);
		$InfoCacheTime = intval($core['info:read'][1]);
		
		$this->assign('HtmlEnable', $HtmlEnable );
		$this->assign('IndexCacheTime', $IndexCacheTime );
		$this->assign('ChannelCacheTime', $ChannelCacheTime);
		$this->assign('InfoCacheTime', $InfoCacheTime );
		$this->assign('Action', __URL__.'/clearCache' );

		$this->display();
	}
	
	function phpinfo(){
		header("Content-Type:text/html; charset=utf-8");
		echo phpinfo();
	}
	
	//获取网站总大小
	function getWebTotalSize(){
		header("Content-Type:text/html; charset=utf-8");
		$size = byte_format(getdirsize('./'));
		$uploadSize = byte_format(getdirsize('./Upload'));
		if( $size > 0 ){ //返回获取值
			$str = $size.'&nbsp;&nbsp;其中上传目录大小为：'.$uploadSize;
			$this->ajaxReturn($str, '' , 1);
		}else{ //获取失败
			$this->ajaxReturn(null, '' , 0);
		}
	}
}